<template>
  <view class="settings-container">
    <!-- 头部 -->
    <view class="header">
      <view class="header-bg"></view>
      <text class="title">个人信息设置</text>
    </view>

    <!-- 个人信息表单 -->
    <view class="form-section">
      <!-- 头像设置 -->
      <view class="form-item avatar-item">
        <text class="label">头像</text>
        <view class="avatar-wrapper">
          <image :src="userInfo.avatarUrl || '/static/profile/defaultAvatar.png'" class="avatar" />
          <button class="avatar-btn" open-type="chooseAvatar" @chooseavatar="onChooseAvatar($event)">
            <text class="btn-text">更换头像</text>
            <text class="btn-icon">></text>
          </button>
        </view>
      </view>

      <!-- 用户名设置 -->
      <view class="form-item">
        <text class="label">用户名</text>
        <input 
          type="nickname"
          v-model="userInfo.userName" 
          placeholder="请输入用户名"
          class="input"
          @blur="onNicknameChange($event)"
        />
      </view>

      <!-- 手机号显示 -->
      <view class="form-item">
        <text class="label">手机号</text>
        <input
            class="input"
            type="number"
            v-model="userInfo.phone"
            placeholder="请输入手机号"
            maxlength="11"
        />
      </view>

      <!-- 邮箱设置 -->
      <view class="form-item">
        <text class="label">邮箱</text>
        <input 
          type="text" 
          v-model="userInfo.email" 
          placeholder="请输入邮箱"
          class="input"
        />
      </view>
    </view>

    <!-- 保存按钮 -->
    <view class="button-section">
      <button class="save-btn" @click="saveSettings">保存修改</button>
    </view>
  </view>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue';
import { useLoginUserStore } from '@/store/loginUserStore';
import { tokenStore } from '@/store/tokenStore';
import { uploadFileUsingPost, updateMyUserUsingPost } from '@/backend';
import { delayNavigateBack } from '@/utils/navigate';
import type { API } from '../../backend/typings';

const loginStore = useLoginUserStore();

const userInfo = ref<API.LoginUserVO>({
  userName: loginStore.getLoginUser.userName || undefined,
  phone: loginStore.getLoginUser.phone || undefined,
  email: loginStore.getLoginUser.email || undefined,
  avatarUrl: loginStore.getLoginUser.avatarUrl || undefined,
  id: undefined,
  createTime: undefined,
  updateTime: undefined,
  openid: undefined,
  userRole: undefined
});

onMounted(() => {
  const storedUser = loginStore.getLoginUser;
  if (storedUser) {
    userInfo.value = { ...storedUser };
  }
});

// 格式化手机号
const formatPhone = (phone: string | null) => {
  if (!phone) return '未绑定';
  return `${phone.slice(0, 3)}****${phone.slice(7)}`;
};

// 处理头像选择
const onChooseAvatar = async (e: any) => {
  const tempFilePath = e.detail.avatarUrl;
  try {
    const uploadRes = await uploadFileUsingPost(
      { filePath: tempFilePath },
      { biz: 'avatar' }
    );

    if (uploadRes.code === 0) {
      userInfo.value.avatarUrl = uploadRes.data;
      uni.showToast({
        title: '头像更新成功',
        icon: 'success'
      });
    } else {
      throw new Error(uploadRes.message || '上传失败');
    }
  } catch (error) {
    console.error('头像上传失败：', error);
    uni.showToast({
      title: '头像上传失败',
      icon: 'error'
    });
  }
};

// 处理昵称变更
const onNicknameChange = (e: any) => {
  const newNickname = e.detail.value;
  if (newNickname) {
    userInfo.value.userName = newNickname;
  }
};

// 保存设置
const saveSettings = async () => {
  try {
    const response = await updateMyUserUsingPost(userInfo.value);

    if (response.code === 0) {
      loginStore.setLoginUser(userInfo.value);
      uni.showToast({
        title: '保存成功',
        icon: 'success'
      });
      delayNavigateBack();
    } else {
      uni.showToast({
        title: response.message,
        icon: 'error'
      });
    }
  } catch (error) {
    uni.showToast({
      title: '保存失败',
      icon: 'error'
    });
    console.error('保存设置失败：', error);
  }
};
</script>

<style scoped>
.settings-container {
  min-height: 100vh;
  background-color: #f8f8f8;
  padding: 0;
}

.header {
  background: linear-gradient(135deg, #ff9800, #ff5722);
  padding: 40rpx 32rpx;
  position: relative;
  overflow: hidden;
  margin-bottom: 24rpx;
}

.header-bg {
  position: absolute;
  top: -50%;
  left: -50%;
  width: 200%;
  height: 200%;
  background: radial-gradient(circle, rgba(255,255,255,0.1) 0%, rgba(255,255,255,0) 70%);
  animation: rotate 20s linear infinite;
}

@keyframes rotate {
  from { transform: rotate(0deg); }
  to { transform: rotate(360deg); }
}

.title {
  font-size: 40rpx;
  font-weight: 600;
  color: #fff;
  text-shadow: 0 2rpx 4rpx rgba(0, 0, 0, 0.2);
  position: relative;
  z-index: 1;
}

.form-section {
  background-color: #fff;
  margin: 24rpx;
  padding: 32rpx;
  border-radius: 24rpx;
  box-shadow: 0 4rpx 16rpx rgba(0, 0, 0, 0.06);
}

.form-item {
  display: flex;
  align-items: center;
  padding: 24rpx 0;
  border-bottom: 2rpx solid #f5f5f5;
}

.form-item:last-child {
  border-bottom: none;
}

.avatar-item {
  align-items: flex-start;
}

.label {
  width: 80px;
  font-size: 16px;
  color: #333;
  font-weight: 500;
}

.avatar-wrapper {
  display: flex;
  flex-direction: column;
  align-items: center;
}

.avatar {
  width: 140rpx;
  height: 140rpx;
  border-radius: 50%;
  margin-bottom: 16rpx;
  border: 6rpx solid rgba(255, 87, 34, 0.1);
  box-shadow: 0 4rpx 16rpx rgba(0, 0, 0, 0.1);
  transition: transform 0.3s ease;
}

.avatar:active {
  transform: scale(0.95);
}

.avatar-btn {
  margin-top: 16rpx;
  background: transparent;
  border: none;
  font-size: 28rpx;
  color: #ff5722;
  padding: 12rpx 32rpx;
  display: flex;
  align-items: center;
  gap: 8rpx;
  transition: all 0.3s ease;
}

.btn-text {
  font-weight: 500;
}

.btn-icon {
  font-size: 24rpx;
  opacity: 0.8;
}

.input {
  flex: 1;
  height: 80rpx;
  padding: 0 24rpx;
  font-size: 28rpx;
  color: #333;
  background-color: #f8f8f8;
  border-radius: 16rpx;
  transition: all 0.3s ease;
}

.input:focus {
  background-color: #f0f0f0;
  box-shadow: inset 0 2rpx 8rpx rgba(0, 0, 0, 0.05);
}

.value {
  flex: 1;
  font-size: 16px;
  color: #666;
}

.button-section {
  margin-top: 32px;
  padding: 0 16px;
}

.save-btn {
  width: 100%;
  height: 88rpx;
  background: linear-gradient(135deg, #ff9800, #ff5722);
  color: #fff;
  font-size: 32rpx;
  font-weight: 600;
  border-radius: 44rpx;
  border: none;
  box-shadow: 0 8rpx 16rpx rgba(255, 87, 34, 0.2);
  display: flex;
  align-items: center;
  justify-content: center;
  transition: all 0.3s ease;
}

.save-btn:active {
  transform: scale(0.98);
  box-shadow: 0 4rpx 8rpx rgba(255, 87, 34, 0.2);
}
</style>